package com.lc.pianostudent.activity;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.view.View;

import com.lc.pianostudent.R;
import com.lc.pianostudent.model.MyService;

/**
 * Created by Administrator on 2018/8/27.
 */

public class ServiceActivity extends BaseActivity{

    private boolean is_binder = false;
    private MyService myService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service);
        final Intent intent = new Intent(this, MyService.class);
        findViewById(R.id.start_video).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bindService(intent, mServiceConnection,
                        Service.BIND_AUTO_CREATE);

            }
        });
        findViewById(R.id.stop_video).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unbindService(mServiceConnection);
            }
        });

    }

    // 服务端和客户端的桥梁
    private ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
            is_binder = false;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //绑定成功，获取到Service的实例对象
            MyService.LocalBinder localBinder = (MyService.LocalBinder) service;
            myService = localBinder.getService();
            is_binder = true;

            Parcel data = Parcel.obtain();
//            data.writeInt(1);
            data.writeString("123");

            Parcel reply = Parcel.obtain();
            try {
                //参数2和3分别是传送过去的数据和反馈的数据
                localBinder.transact(IBinder.LAST_CALL_TRANSACTION, data, reply, 0);
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (is_binder) {
            unbindService(mServiceConnection);
        }
    }

    private void ini(){

    }
}
